package com.service.proxy;

import java.net.InetSocketAddress;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.pub.dbo.constant.Global;
import com.pub.dbo.domain.Country;
import com.pub.dbo.impl.CountryImpl;
import com.service.pub.ParameterFilter;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.spi.HttpServerProvider;



public class ProxyService implements Global
{
	private static int port = 8425;
	
	private static int threadMinCount 	= 100;
	private static int threadMaxCount 	= 200;
	private static int checkPeriod 		= 2;
	
	private static String context = "/ProxyItem";
	
	private Country country;
	private CountryImpl countryImpl;
	
	static
	{
	}

	/**
	 * 
	 */
	public ProxyService() 
	{
		
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) 
	{
		if(args.length == 1){
			ProxyService service = new ProxyService();
			if(service.init(args[0])){
				service.handle();
			}else{
				System.out.println("parameter errer. Useage : xx.sh countryCode");
			}
			
		}else{
			System.out.println("parameter errer. Useage : xx.sh countryCode");
		}
	}
	
	public boolean init(String countryCode)
	{
		boolean isReturn = true;
		
		countryImpl = new CountryImpl(DBTAG_GLOBAL);
		
		country 	= countryImpl.getCountry(countryCode);
		
		if(country == null){
			isReturn = false;

			System.out.println("can't find country by country code " + countryCode);
		}
		
		return isReturn;
	}
	
	@SuppressWarnings("unchecked")
	public void handle()
	{
		HttpServerProvider httpServerProvider = HttpServerProvider.provider();  
        InetSocketAddress addr = null;  
        HttpServer httpServer = null;  
        try {
        	ThreadPoolExecutor threadPool = new ThreadPoolExecutor(threadMinCount, threadMaxCount, checkPeriod, TimeUnit.SECONDS, new ArrayBlockingQueue(100), new ThreadPoolExecutor.CallerRunsPolicy()); 
             
            addr = new InetSocketAddress(port);  
            httpServer = httpServerProvider.createHttpServer(addr, 1);  
            HttpContext httpContext = httpServer.createContext(context, new ProxyHttpHandler(country.getCrawlerDBName()));  
            httpContext.getFilters().add(new ParameterFilter());
            
            httpServer.setExecutor(threadPool);  
            httpServer.start();
            
        } catch (Exception e) {  
            e.printStackTrace();  
        }
	}
}